
package com.huawei.saashousekeeper.interceptor;

import com.huawei.saashousekeeper.config.TenantContext;

import lombok.extern.log4j.Log4j2;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;

import java.util.Map;

/**
 * 消息切面
 *
 * @author lWX1128557
 * @since 2022-03-17
 */
@Aspect
@Log4j2
public class RabbitMqAspect {
    /**
     * 切点
     */
    @Pointcut("@annotation(com.huawei.saashousekeeper.annotation.MqAround)")
    public void mqAroundAdvice() {
    }

    /**
     * 消息接收时做租户路由
     *
     * @param joinPoint
     */
    @Around("mqAroundAdvice()")
    public void aroundAdvice(ProceedingJoinPoint joinPoint) {
        String method = joinPoint.getSignature().getName();

        // 接收消息前初始化豪猪 TODO 根据消息接收的实际场景设计，最好是从消息体中获取参数，而不是方法中获取
        Object messageHerder = joinPoint.getArgs()[0];
        if (messageHerder instanceof Map) {
            Map<String, Object> headers = (Map<String, Object>) messageHerder;
            TenantContext.set((String) headers.get("tenantDomain"));
        } else {
            TenantContext.set((String) messageHerder);
        }
        try {
            joinPoint.proceed();
        } catch (Throwable throwable) {
            log.error(throwable.getMessage(), throwable);
        } finally {

            // 方法执行后移除租户标识
            TenantContext.remove();
        }
        log.info("aspect Method: " + method);
    }
}
